// import $store from "@/store/index.js"
import $baseUrl from "@/config/index.js"
export default {
	// 全局配置
	common: {
		// 根目录
		baseUrl: $baseUrl.baseUrl + 'api/',
		header: {
			'Content-Type': 'application/json;charset=UTF-8',
			// 'Content-Type': 'application/x-www-form-urlencoded'
		},
		data: {},
		method: 'GET',
		dataType: 'json'
	},
	// 请求 ,返回Promise
	request(options = {}) {
		// 组织参数
		options.url = this.common.baseUrl + options.url
		options.header = options.header || this.common.header
		options.data = options.data || this.common.data
		options.method = options.method || this.common.method
		options.dataType = options.dataType || this.common.dataType
		if(options.token){
			// console.log(uni.getStorageSync('token'))
			options.header.token = uni.getStorageSync('token')
			// 如果options.header.token为null时,进行二次验证,
			// checkToken == true必须要验证token
			if(options.checkToken && !options.header.token){
				uni.showToast({
					title:'请先登录',
					icon:'none'
				})
				return uni.navigateTo({
					url:'/pages/login/login'
				})
			}
		}
		return new Promise((res, rej) => {
			uni.request({
				...options,
				success: (result) => {
					// 返回原始数据
					if (options.native) {
						return res(result)
					}
					if (result.data.code == 0) {
						uni.showToast({
							title: result.data.msg,
							icon: 'none'
						});
					}
					// 服务端失败
					if (result.data.code == 401) {
						uni.showToast({
							title: result.data.msg,
							icon: 'none'
						});
						uni.navigateTo({
							url:'/pages/login/login'
						})
						// 失败
						return rej()
					}
					// 成功
					let data = result.data
					res(data)
				},
				fail: (error) => {
					uni.showToast({
						title: error.errMsg || '请求失败',
						icon: 'none'
					});
					// 失败
					return rej()
				}
			})
		})
	},
	// get请求
	get(url, data = {}, options = {}) {
		options.url = url
		options.data = data
		options.method = 'GET'
		return this.request(options)
	},
	// post请求
	post(url, data = {}, options = {}) {
		options.url = url
		options.data = data
		options.method = 'POST'
		return this.request(options)
	},
	// delete请求
	delete(url, data = {}, options = {}) {
		options.url = url
		options.data = data
		options.method = 'DELETE'
		return this.request(options)
	}
}
